package cate.game.role.world.beta;

import cate.common.table.d.GDObj;
import cate.common.table.d.GDOperation;
import cate.game.GameBody;
import cate.game.mail.po.MailBuilder;
import cate.game.res.MixRes;
import cate.game.role.Role;
import cate.game.role.RoleDependent;
import cate.game.util.ct.CT;
import cp.solution.business.world.beta.BetaPayHistory;
import easy.java.dev.note.NoteField;
import easy.java.time.DateTool;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class MyBeta extends RoleDependent {

    public static final boolean enabled = true;
    private static final long ENABLE_TIME = 1663048457602L;

    @NoteField("已经执行过返利")
    public boolean payRefund;

    @NoteField("封测期间账户总充值数")
    public long paySum;

    @Override
    public void initialize(Role role) {
        super.initialize(role);
    }

    @Override
    public void onEnter() {
        super.onEnter();
        if(!enabled) {
            return;
        }
        GameBody game = role.getGame();
        long openTs = game.config.gs.getOpenTime().getTime();
        if(openTs < ENABLE_TIME) {
            // 在此之前开服的服，不执行该逻辑
            log.info("在此({})之前开服的服({})，不执行该逻辑 {}", DateTool.instance().format(ENABLE_TIME), DateTool.instance().format(openTs));
            return;
        }
        if(!this.payRefund) {
            this.payRefund = true;
            try {
                if(game.world.betaPay.skipRefund(role.getBase().openId)) {
                    log.info("通过本服判断就足以知道不需要去world-server查询返利了 openId={}", role.getBase().openId);
                    return;
                }
                long beginTime = System.currentTimeMillis();
                BetaPayHistory history = game.apis().world.beta.refundPayHistory(role.getBase().openId);
                long costTime = System.currentTimeMillis() - beginTime;
                CT.gs(game).addPayRefundTime(costTime);
                if(history != null && !history.refund) {
                    log.info("试图封测支付返还,数据查询成功 {}", history);
                    this.paySum = history.paySum;
                    MailBuilder mailBuilder = new MailBuilder();
                    mailBuilder.setContent("您获得了封测返利").setTitle("封测充值返还")
                            .setReward(MixRes.buildSimple(GDObj.Type.NUM, GDObj.Num.M1, history.paySum*3/10))
                            .setOperation(GDOperation.BETA_PAY_REFUND);
                    role.getMail().add(mailBuilder.build());
                } else {
                    log.debug("不需要封测支付返还");
                }
                log.info("试图封测支付返还 costTime={}", costTime);
            } catch (Exception e) {
                log.error("试图封测支付返还 出错 账户信息openId={}", role.getBase().openId);
                log.error("", e);
            }
        }
    }
}
